# !/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
@作者 杨阳
@时间 2018-06-01
@说明 自动生成代码
@注意事项 需要自生行添加外键
"""
import json

from sqlalchemy.sql.functions import current_time

from util.JsonUtil import classToDict, JsonEncoder
from util.StrUtil import get_uuid
from util.ThreadPluginsInitUtil import db


class TWorkerModel(db.Model):
    """
    与t_worker表对应的实体类
    """
    __tablename__ = 't_worker'
    id = db.Column(db.String(36), primary_key=True, index=True, nullable=False, comment='''''')
    name = db.Column(db.String(100), nullable=True, comment='''''')
    user = db.Column(db.String(255), nullable=True, comment='''''')
    days = db.Column(db.Integer, nullable=True, comment='''''')
    create_time = db.Column(db.DateTime, nullable=True, comment='''''')

    @staticmethod
    def get_entity_byId(id):
        """
        根据id获得实体类对象
        :param   id  实体类id
        """
        entity = TWorkerModel.query.filter(TWorkerModel.id == id).first()
        return entity

    @staticmethod
    def delete_entity_byId(id):
        """
        根据id删除数据
        :param   id  实体类id
        """
        try:
            entity = TWorkerModel.get_entity_byId(id)
            db.session.delete(entity)
            db.session.commit()
            result = {"success": True, "msg": "删除成功!"}
        except Exception as err:
            db.session.rollback()
            result = {"success": True, "msg": "删除失败，请重试!"}
        finally:
            pass
        return json.dumps(result)

    @staticmethod
    def add_entity(name, user, days):
        """
        增加实体类
        :param   name  
        :param   user  
        :param   days  
        """
        try:
            entity = TWorkerModel()
            entity.id = get_uuid()
            entity.name = name
            entity.user = user
            entity.days = days
            entity.create_time = db.cast(current_time(), db.DateTime)
            db.session.add(entity)
            db.session.commit()
            result = {"success": True, "msg": "增加成功!"}
        except Exception as err:
            db.session.rollback()
            result = {"success": True, "msg": "增加失败，请重试!"}
        finally:
            pass
        return json.dumps(result)

    @staticmethod
    def update_entity(id, name, user, days):
        """
        修改数据库
        :param   id  
        :param   name  
        :param   user  
        :param   days  
        """
        try:
            entity = TWorkerModel.get_entity_byId(id)
            entity.id = id
            entity.name = name
            entity.user = user
            entity.days = days
            db.session.commit()
            result = {"success": True, "msg": "修改成功!"}
        except Exception as err:
            db.session.rollback()
            result = {"success": True, "msg": "修改失败，请重试!"}
        finally:
            pass
        return json.dumps(result)

    @staticmethod
    def query_entity_grid(group_id, search_name, search_user, search_days, search_start_create_time,
                          search_end_create_time, current_page=1):
        """
        查询表格数据
        """
        filters = {1 == 1}
        if search_name is not None and search_name != '':
            filters.add(TWorkerModel.name.like("%" + search_name + "%"))
        if search_user is not None and search_user != '':
            filters.add(TWorkerModel.user.like("%" + search_user + "%"))
        if search_days is not None and search_days != '':
            filters.add(TWorkerModel.days == search_days)
        if search_start_create_time is not None and search_start_create_time != '':
            filters.add(TWorkerModel.create_time >= search_start_create_time)
        if search_end_create_time is not None and search_end_create_time != '':
            filters.add(TWorkerModel.create_time <= search_end_create_time)
        # 查询数据集合
        entity_list = TWorkerModel.query.filter(*filters).order_by(TWorkerModel.create_time.desc()).limit(10).offset(
            (int(current_page) - 1) * 10)
        # 查询总记录数
        total = db.session.query(TWorkerModel.id).filter(*filters).count()
        list = []
        for obj in entity_list:
            list.append(classToDict(obj))
        retu = {"success": True, "grid": list, "total_count": total}
        result = json.dumps(retu, cls=JsonEncoder)
        return result
